module Login exposing (..)

import Html exposing (Html, a, button, code, div, h1, li, text, ul, br,input)
import Html.Events exposing (onInput, onClick)
import Http
import Json.Encode as Encode
import Json.Decode as Decode
import Navigation

type Msg 
 = InputName String
 | InputPass String
 | Confirm
 | LoginResult (Result Http.Error (Result String String))

type Model =
 Model Name Pass Log

type alias Name = String
type alias Pass = String
type alias Log = String

initModel = Model "" "" ""

view : Model -> Html Msg
view (Model name pass log) =
 div []
  [ text "请登录"
  , br [] []
  , text "用户名" , input [onInput InputName] []
  , br [] []
  , text "密码" , input [onInput InputPass] []
  , br [] []
  , button [onClick Confirm] [text "登录"]
  , br [] []
  , text ("Logger: " ++ log)]
         


update : Msg -> Model -> (Model,Cmd Msg)
update msg ((Model oldName oldPass log) as model) =
 case msg of
  InputName name -> (Model name oldPass log,Cmd.none)
  InputPass pass -> (Model oldName pass log,Cmd.none)
  Confirm ->
   let
    url = "/login"
    json = Encode.object [("name",Encode.string oldName),("pass",Encode.string oldPass)]
    body = Http.jsonBody json
    decoder = Decode.oneOf [Decode.map Ok (Decode.field "ok" Decode.string),Decode.map Err (Decode.field "err" Decode.string)]
    request = Http.post url body decoder
   in
    (model, Http.send LoginResult request)
  
  LoginResult (Err _) -> (Model oldName oldPass "服务器响应错误!",Cmd.none)
  LoginResult (Ok res) ->
   case res of
    Err err -> (Model oldName oldPass ("登录失败: " ++ err) ,Cmd.none)
    Ok _ -> (Model oldName oldPass ("登录成功") ,Navigation.newUrl "#/nodes/0")
